<?php 
require_once( dirname(__FILE__).'/../libs/bedmintonlib.php' );

function loginUser( $login, $password, & $outMessage )
{
    $db = Db::db();
    $dbConnection = $db->connection();
    if (is_null( $dbConnection ))
    {
        $outMessage = $db->getErrorStr();
        return;
    }

    try
    {
        $statement = $dbConnection->prepare( "SELECT id, name, surname, passwordhash, passwordsalt, state, passwordtochange FROM customers WHERE emailaddress = ?");
        $statement->bindParam( 1, $login, PDO::PARAM_STR );
        $statement->execute();
        $obj = $statement->fetch( PDO::FETCH_OBJ );
        if (! $obj)
        {
            $outMessage = isEnglish() ? "Login not exists for the user" : "Tento email nebol zaregistrovaný";
            return;
        }
        
        $loggedUser = new LoggedUser();
        $loggedUser->id = $obj->id;
        $loggedUser->emailAddress = $login;
        $loggedUser->name = $obj->name;
        $loggedUser->surname = $obj->surname;
        if (! isset( $obj->passwordtochange ) || $obj->passwordtochange != $password )
        {
            if (!PasswordHash::verifyPasswordHash( $password, $obj->passwordsalt, $obj->passwordhash ))
            {
                $outMessage = isEnglish() ? "Invalid password" : "Nesprávne heslo";
                return;
            }
        }
        
        switch ($obj->state)
        {
            case 0:
                $outMessage = isEnglish() ? "User is not active and needs to be confirmed" : "Používateľ ešte nebol aktivovaný.";
                return;
            
            case 1:
                break;
            
            case 2:
                $outMessage = isEnglish() ? "User is blocked" : "Používateľ bol zablokovaný. Kontaktujte správcu.";
                return;
            
            default:
                $outMessage = isEnglish() ? "Unknown state" : "Neznámy stav";
                return;
        }
        
        $_SESSION[ 'logged_user' ] = serialize( $loggedUser );
        WebStat::logLoginUser( $loggedUser->emailAddress );
    }
    catch(PDOException $e)
    {
        $outMessage = $e->getMessage();
        return;
    }
    
    redirectToMainSite( "reservation.php" );
    exit;
}

$echoStr = "";
if ( ! isset( $_POST[ 'login' ] ) || ! isset( $_POST[ 'password' ] )  )
{
    $echoStr = "No data";
}
else
{
    loginUser(  $_POST[ 'login' ], $_POST[ 'password' ], $echoStr );
}

showError( $echoStr );

?>
